package logic

import (
	"context"
	"fmt"
	"user/model/mysql"
	"user/model/redis"
	"user/pkg"

	"user/userrpc/internal/svc"
	"user/userrpc/userrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type UserUpdateLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUserUpdateLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserUpdateLogic {
	return &UserUpdateLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *UserUpdateLogic) UserUpdate(in *userrpc.UserUpdateRequest) (*userrpc.UserUpdateResponse, error) {
	// todo: add your logic here and delete this line
	get := redis.Client.Get("captChaUpdate" + in.Phone)
	if get.Val() != in.CaptChaCode {
		return nil, fmt.Errorf("图形验证码输入错误,请重新输入")
	}
	sms := redis.Client.Get("sendSmsUpdate" + in.Phone)
	if sms.Val() != in.SendSmsCode {
		return nil, fmt.Errorf("短信验证码输入错误,请重新输入")
	}
	var user mysql.User
	mysql.DB.Debug().Where("phone = ?", in.Phone).Find(&user)
	if user.ID == 0 {
		return nil, fmt.Errorf("该用户未注册,请前去注册")
	}
	if user.Password != pkg.Md5Pwd(in.OldPassword) {
		return nil, fmt.Errorf("您输入的旧密码错误,请重新输入")
	}
	user.Password = pkg.Md5Pwd(in.NewPassword)
	err := mysql.DB.Debug().Updates(&user).Error
	if err != nil {
		return nil, fmt.Errorf("修改密码失败")
	}
	redis.Client.Del("captChaUpdate" + in.Phone)
	redis.Client.Del("sendSmsUpdate" + in.Phone)
	return &userrpc.UserUpdateResponse{Id: int64(user.ID)}, nil
}
